package peer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import org.jdesktop.jdic.desktop.DesktopException;

import peer.tools.FileTools;

public class FolderSynThread implements Runnable {
	Thread mainThread = null;

	static boolean first = true;

	FolderSynThread() {
		mainThread = new Thread(this);
		mainThread.start();
	}

	public void run() {
		while (true) {
			new Thread() {
				public void run() {
					synNow();
					if(Ui.openfolder){
						File file = new File("player.exe");
						if (file.exists()) {
							try {
								org.jdesktop.jdic.desktop.Desktop.open(file);
							} catch (DesktopException e) {
								e.printStackTrace();
							}
						}
						try {
							Runtime.getRuntime().exec("Explorer.exe " + peer.Config.getSynPath());
						} catch (IOException e) {
							e.printStackTrace();
						}
						Ui.openfolder=false;
					}
					first = false;
				}
			}.start();
			try {
				Thread.sleep(Config.synFolderInterval);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void synNow(){
		String path =peer.Config.getSynPath();
		File folderFile = new File(path);
		if(!folderFile.exists()){
			folderFile.mkdir();
		}
		for (int i = 0; i < 5; i++) {
			try {
				URL url = null;
				url = new URL(Config.synFolderUrl);
				URLConnection ucn = url.openConnection();
				if ((ucn.getLastModified() - Config
						.getLastFolderSynTime()) / 1000 > 0
						| !folderFile.exists()|first) {

					FilterInputStream in = (FilterInputStream) url
							.openStream();
					String fn="synfolder"+peer.tools.RandomNum.randomInt()+".zip";
					final File file = new File(fn);
					FileOutputStream out = new FileOutputStream(file);
					byte[] bytes = new byte[1024];
					int c;
					while ((c = in.read(bytes)) != -1) {
						out.write(bytes, 0, c);
					}
					in.close();
					out.close();
					FileTools.cleanDir(path);
					try {
						FileTools.unZip(fn, path);
					} catch (Exception e) {
						e.printStackTrace();
					}
					file.delete();
					Config.setLastFolderSynTime(ucn.getLastModified());
				}
				
				Config.updateSynFolderLink();
				break;
			} catch (IOException e1) {
				//e1.printStackTrace();
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

